<script setup>
import { ref } from "vue"
import { showToast } from 'vant'
import { useRouter, useRoute } from "vue-router";
import { login, register } from "@/api/user";
import { useUserStore } from "@/stores/store";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 表单数据
const form_login = ref({
    username: '',
    password: ''
});

const form_register = ref({
    username: '',
    password: '',
    email:'',
    phone:'',
    roleId:3
});

// 页面状态
const page = ref('login');

// 验证函数
const validatePhone = (val) => {
    if (!val) return true; // 允许为空
    return /^1[3-9]\d{9}$/.test(val);
};

const validateEmail = (val) => {
    if (!val) return true; // 允许为空
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(val);
};

// 登录处理
const loginToMain = async () => {
    if (!form_login.value.username) {
        showToast('请输入用户名');
        return;
    }
    
    if (!form_login.value.password) {
        showToast('请输入密码');
        return;
    }

    try {
        const res = await login({
            username:form_login.value.username,
            password:form_login.value.password,
            rolekey:'user'
        });
        console.log(res)
        if (res) {
            userStore.setToken(res.token);
            userStore.setUserId(res.currentUser.id);
            showToast('登录成功');
            router.push('/home');
        } else {
            showToast( '登录失败');
        }
    } catch (error) {
        showToast('登录失败');
        console.error('登录错误:', error);
    }
}

const registerToMain = async () => {
    if (!form_register.value.username) {
        showToast('请输入用户名');
        return;
    }
    
    if (!form_register.value.password) {
        showToast('请输入密码');
        return;
    }
    if (form_register.value.phone && !validatePhone(form_register.value.phone)) {
        showToast('请输入正确的手机号');
        return;
    }
    
    if (form_register.value.email && !validateEmail(form_register.value.email)) {
        showToast('请输入正确的邮箱');
        return;
    }

    try {
        const res = await register(form_register.value);
        const data=await login({
            username:form_register.value.username,
            password:form_register.value.password,
            rolekey:'user'
        })
        if (data) {
            userStore.setToken(data.token);
            userStore.setUserId(res.currentUser.id);
            showToast('注册成功');

            // 获取登录前想要访问的页面路径
            const redirect = route.query.redirect;
            // 如果有重定向地址则跳转到重定向地址，否则跳转到首页
            router.replace(redirect || '/home');
        } else {
            showToast(res.msg || '注册失败');
        }
    } catch (error) {
        showToast('注册失败');
        console.error('注册错误:', error);
    }
};

// 页面切换
const toRegister = () => {
    page.value = 'register';
    resetForms();
};

const toLogin = () => {
    page.value = 'login';
    resetForms();
};

// 重置表单
const resetForms = () => {
    form_login.value = {
        username: '',
        password: ''
    };
    
    form_register.value = {
        username: '',
        password: '',
        email:'',
        phone:'',
        roleId:3
    };
};
</script>
<template>
  <div class="welcome">
    <!-- 背景 -->
    <div class="round round-1"></div>
    <div class="round round-2"></div>
    <div class="round round-3"></div>
    <div class="round round-4"></div>

    <div class="content">
        <button @click.prevent="toLogin" :class="{ active: page === 'login' }" class="btn-welcome btn-register">前往登录</button>

        <h2 class="title title_login" :class="{ active: page === 'register' }">欢迎登录</h2>
        <h2 class="title title_register" :class="{ active: page === 'login' }">欢迎注册</h2>

        <div class="form-login form" :class="{ active: page === 'register' }">
            <van-form>
                <van-cell-group inset>
                    <van-field
                        class="input-upper"
                        v-model="form_login.username"
                        label="用户名"
                        placeholder="请输入用户名"
                        :rules="[{ required: true, message: '请填写用户名' }]"
                    />
                    <van-field
                        class="input-lower input-password"
                        v-model="form_login.password"
                        label="密码"
                        type="password"
                        placeholder="请输入密码"
                        :rules="[{ required: true, message: '请输入密码' }]"
                    >
                    </van-field>
                </van-cell-group>
            </van-form>

            <button class="btn-round btn-login-to-main" @click.prevent="loginToMain">登录</button>
        </div>
        <div class="form-register form" :class="{ active: page === 'login' }"> 
            <van-form >
                <van-cell-group inset>
                    <van-field
                        class="input-upper"
                        v-model="form_register.username"
                        label="用户名"
                        placeholder="请输入用户名"
                        :rules="[{ required: true, message: '请填写用户名' }]"
                    />
                    <van-field
                        class="input-upper input-password"
                        v-model="form_register.password"
                        label="密码"
                        type="password"
                        placeholder="请输入密码"
                        :rules="[{ required: true, message: '请填写密码' }]"
                    />
                    <van-field
                        class="input-upper"
                        v-model="form_register.phone"
                        label="手机号"
                        placeholder="请输入手机号（选填）"
                        :rules="[{ validator: validatePhone, message: '请输入正确的手机号' }]"
                    />
                    <van-field
                        class="input-upper"
                        v-model="form_register.email"
                        label="邮箱"
                        placeholder="请输入邮箱（选填）"
                        :rules="[{ validator: validateEmail, message: '请输入正确的邮箱' }]"
                    />
                </van-cell-group>
            </van-form>
            <button class="btn-round btn-register-to-main" @click.prevent="registerToMain">注册</button>
        </div>
        <button @click.prevent="toRegister" :class="{ active: page === 'register' }" class="btn-welcome btn-login">前往注册</button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@use '@/assets/scss/abstracts/variables' as *;
@use '@/assets/scss/abstracts/mixins' as *;
@use '@/assets/scss/base/base' as *;
@use '@/assets/scss/components/btn' as *;
@use '@/assets/scss/base/animation' as *;
@use 'sass:color';

.welcome {
    width: 100%;
    height: 100vh;
    position: relative;
    overflow: hidden;

    @include flexCenter;

    background: linear-gradient(30deg, rgba($color-primary-light, 0.2),
    rgba($color-primary-light, 0.1),
    rgba($color-primary-light, 0.2));
    z-index: 1;
}

.round{
    width: 5rem;
    height: 5rem;
    border-radius: 50%;
    background-color: $color-primary-light;
    box-shadow: 0 0.4rem 0.6rem rgba($color-black, 0.1);

    position: absolute;

    &-1{
        top: -2rem;
        left: -.5rem;
        z-index: 10;
    }

    &-2{
        top: -.5rem;
        left: -2rem;
        z-index: 5;
        background-color: color.adjust($color-primary-light, $lightness: -5%);
    }

    &-3{
        bottom: -2rem;
        right: -1rem;
        z-index: 10;
    }

    &-4{
        bottom: -.5rem;
        right: -2.5rem;
        z-index: 5;
        background-color: color.adjust($color-primary-light, $lightness: -5%);
    }
}

.content{
    @include flexColumnCenter;
    gap: 1rem;
    width: 100%;
    margin-bottom: 1rem;

    .title{
        margin-bottom: .5rem;

        &_login{
            display: block;
            animation: move-right .4s ease-in-out forwards;
            
            &.active{
                display: none;
            }
        }

        &_register{
            display: block;
            animation: move-left .4s ease-in-out forwards;

            &.active{
                display: none;
            }
        }
    
    }
}

.form{
    margin-bottom: .5rem;
    min-height: 8rem;

    &-login{
        align-self: flex-start;
        width: 75%;
        transition: transform .4s ease-in-out;
        animation: move-right .4s ease-in-out forwards;
        display: block;

        &.active{
            display: none;
        }

        :deep(.van-cell-group){
            border-radius: 0 2rem 2rem 0;
            padding-left: .2rem;
        }

        :deep(.van-cell__title){
            position: absolute;
            color: $color-grey-1;
            font-size: 14px;
            top: .1rem;
            left: .1rem;
        }

        :deep(.van-field__body){
            margin-top: .8rem;
            margin-left: 1.2rem;
            font-size: 16px;
        }

        :deep(.van-field__error-message){
            margin-left: 1.2rem;
            font-size: .4rem;
        }
    }

    &-register{
        align-self: flex-end;
        width: 75%;
        display: none;
        transition: transform .4s ease-in-out;
        animation: move-left .4s ease-in-out forwards;
        display: block;

        &.active{
            display: none;
        }

        :deep(.van-cell-group){
            border-radius: 2rem 0 0 2rem;
            padding-right: .2rem;
        }

        :deep(.van-cell__title){
            position: absolute;
            color: $color-grey-1;
            font-size: 14px;
            top: .1rem;
            left: 1.8rem;
        }

        :deep(.van-field__body){
            margin-top: .8rem;
            margin-left: 2.4rem;
            font-size: 16px;
        }

        :deep(.van-field__error-message){
            margin-left: 2.4rem;
            font-size: .4rem;
        }
    }

    :deep(.van-cell){
        min-height: 2.4rem;
        position: relative;
    }
}

.input-password{
    padding-right: 1.2rem;
}

.btn{
    &-welcome {
        font-weight: 600;
        transition: transform .3s ease-in-out;  
    }
 
    &-login{
        background: linear-gradient(to right top, $color-primary, $color-primary-light);
        border-radius: 0 1rem 1rem 0;
        align-self: flex-start;
        margin-top: -1rem;
        animation: move-right .4s ease-in-out;

        &.active {
            transform: translateX(-100%);
        }
    }

    &-register{
        background: linear-gradient(to left top,   $color-primary, $color-primary-light);
        border-radius: 1rem 0 0 1rem;
        align-self: flex-end;
        transition: transform .3s ease-in-out; 

        &.active{
            transform: translateX(100%);
        }
    }

    &-round{
        width: 2.5rem;
        height: 2.5rem;
        border-radius: 50%;
        background-color: $color-primary-light;
        box-shadow: 0 0.2rem 0.3rem rgba($color-black, 0.1);
        font-size: .5rem;
        border: solid 1px rgba($color-primary, 0.2);

        position: absolute;
        top: 3rem;
        z-index: 1000; 
    }

    &-login-to-main{
        right: -1.4rem;
    }

    &-register-to-main{
        left: -1.3rem;
    }
}
</style>